<?php
namespace PHPSpring\Annotation\Impl;

use PHPSpring\Annotation\IValidator;

/**
 * @Required($message?, array|string $groups?)
 * eg:
 *   @Required
 *   @Required(message='message') or @Required('message')
 *   @Required(message='message', groups='groups') or @Required('message', groups='groups')
 * message format: '%s 必填' => '$fieldName 必填'
 */

class Required implements IValidator {

  public static function validate ($args, $fieldName, $fieldType, $fieldValue, $group=null) {
    self::normalizeArguments($args);
    if (Validation::skipValidateByGroup($group, $args)) {
      return;
    }

    if ($fieldValue === null
        || ($fieldType === 'string' && strlen("$fieldValue") < 1)) {
      return self::getMessage($fieldName, $fieldValue, $args[Validation::MESSAGE_ARG_KEY]);
    }
  }

  public static function normalizeArguments (array &$args) {
    Validation::resetMessageArgs($args, '%s 必填');
  }

  private static function getMessage ($fieldName, $fieldValue, $message) {
    $message = str_replace('%s', $fieldName, $message);
    return $message;
  }
}
